package com.lmf.domain;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 测试 SqlSessionFactory:查询数据库：
 */
public class MyApp {
    /**
        查询操作
     */
    public static void main(String[] args) throws IOException {
        //访问mybatis获取student数据
        //1.mybatis 主配置文件,从类路径的根开始
        String config = "mybatis.xml";
        //2.读取配置文件
        InputStream in = Resources.getResourceAsStream(config);
        //3.创建 SqlSessionFactoryBuilder 对象,目的是获取 SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //4.（重要）获取 SqlSession,SqlSession 能执行 sql 语句
        SqlSession session = factory.openSession();
        //5.（重要）执行 SqlSession 的 selectList() 参数值=namespace+"."+sql标签id值
        List<Student> studentList = session.selectList("com.lmf.dao.StudentDao" + "." + "selectStudents");
        //6.循环输出查询结果
//        studentList.forEach( student -> System.out.println(student));
        for (Student student : studentList) {
            System.out.println(student);
        }
        //7.关闭 SqlSession，释放资源
        session.close();
    }
}
